﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WeatherSystem.Application.ContentAdapter.Base;
using WeatherSystem.Data.Response;

namespace WeatherSystem.Application.ContentAdapter
{
    class ContentManager
    {
        private static Dictionary<Type, Adapter> Adapters = new Dictionary<Type, Adapter>();
        private static Default DefaltAdapter = new Default();
        /// <summary>
        /// 注册一个内容适配器
        /// </summary>
        /// <param name="adapter"></param>
        public static void Register(AdapterBase adapter)
        {
            if (Adapters.ContainsKey(adapter.AdaptType)) return;
            foreach(var a in Adapters.Values)
            {
                if ((a as AdapterBase).Adapt(adapter.AdaptType)) return;
            }
            Adapters.Add(adapter.AdaptType, adapter as Adapter);
        }
        /// <summary>
        /// 获取回复消息
        /// </summary>
        /// <param name="message">用户消息主体</param>
        /// <returns></returns>
        public static ResponseMessageBase GetResponseContent(MsgHandler.Message message)
        {
            var type = message.GetType();
            if (Adapters.ContainsKey(type))
            {
                return Adapters[message.GetType()].Handle(message);
            }
            // 若消息类型为某种适配器适配类型的子类，也可适配
            else
            {
                foreach(var adapter in Adapters.Values)
                {
                    var a = adapter as AdapterBase;
                    if (type.IsSubclassOf(a.AdaptType))
                    {
                        return adapter.Handle(message);
                    }
                }
            }
            return DefaltAdapter.Handle(message);
        }

        public static void Init()
        {
            Register(new TextManager());
            Register(new EventManager());
        }
    }
}
